import asyncio
import h2
import h2.connection
import h2.events
import ssl
from http.server import BaseHTTPRequestHandler, HTTPServer


class HTTP2Server(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        self.wfile.write(b"Hello from HTTP/2 Python server!")
        return


async def handle_client(reader, writer):
    conn = h2.connection.H2Connection(our_role=h2.connection.Role.SERVER)
    # conn = h2.connection.H2Connection()
    conn.initiate_connection()
    await writer.write(conn.data_to_send())

    data = await reader.read(1024)
    events = conn.receive_data(data)

    for event in events:
        if isinstance(event, h2.events.RequestReceived):
            stream_id = event.stream_id
            headers = [(':status', '200'), ('content-type', 'text/plain')]
            conn.send_headers(stream_id, headers)
            conn.send_data(stream_id, b"Hello from HTTP/2 Python server!", end_stream=True)

    await writer.write(conn.data_to_send())
    writer.close()


async def main():
    # 创建一个SSLContext对象
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    # 加载服务器证书和私钥（请替换为你的证书和私钥路径）
    ssl_context.load_cert_chain('sslkey/server.crt', 'sslkey/server.key')

    # 创建一个SSL协议工厂
    ssl_protocol = ssl_context.wrap_socket
    # 使用SSL协议工厂创建服务器
    server = await asyncio.start_server(
        handle_client, '127.0.0.1', 8443, ssl=ssl_protocol
    )
    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

    # server = await asyncio.start_server(
    #     handle_client, '127.0.0.1', 8443, ssl_context=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH))
    #
    # addr = server.sockets[0].getsockname()
    # print(f'Serving on {addr}')
    #
    # async with server:
    #     await server.serve_forever()


# Python 3.7+


asyncio.run(main())
